$(function () {
    console.log('开始初始化实时气象图表...');

    // 图表实例
    let chart1 = null; // 风况
    let chart2 = null; // 气压
    let chart3 = null; // 温度
    let chart4 = null; // 降水

    // 当前选中的地区
    let currentDistrict = '中原区';
    let autoRefreshInterval = null;

    // 图表颜色配置
    const chartColors = {
        wind: '#4cd137',
        pressure: '#ff6b6b',
        temperature: '#f39c12',
        precipitation: '#2e86de'
    };

    // 初始化所有图表
    function initAllCharts() {
        console.log('开始初始化图表...');

        initWindChart();
        initPressureChart();
        initTemperatureChart();
        initPrecipitationChart();

        console.log('图表初始化完成，开始获取数据...');

        // 开始自动刷新
        startAutoRefresh();

        // 默认加载中原区数据
        fetchAndUpdateCharts('中原区');
    }

    // 从后端API获取实时数据
    async function fetchRealTimeData(district) {
        const apiUrl = `/api/realtime-weather/district/${encodeURIComponent(district)}`;
        console.log(`正在请求API: ${apiUrl}`);

        try {
            const response = await fetch(apiUrl);
            console.log(`API响应状态: ${response.status}`);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            console.log(`API返回数据:`, data);

            // 检查数据是否有效
            if (!data || !data.data || !Array.isArray(data.data)) {
                throw new Error('Invalid data format');
            }

            // 为数据添加时间戳
            const processedData = data.data.map(item => {
                if (!item.timestamp && item.timeDisplay) {
                    const [hours, minutes] = item.timeDisplay.split(':').map(Number);
                    const now = new Date();
                    const approxTime = new Date(now);
                    approxTime.setHours(hours, minutes, 0, 0);
                    item.timestamp = approxTime.toISOString();
                }
                return item;
            });

            data.data = processedData;

            console.log(`获取到 ${data.data.length} 条数据`);
            return data;
        } catch (error) {
            console.error('获取实时数据失败:', error);
            // 返回模拟数据作为降级方案
            console.log('使用模拟数据作为降级方案');
            return getMockData(district);
        }
    }
   //Flink状态检查
    async function checkFlinkStatus() {
        try {
            const response = await fetch('/api/flink/status');
            const status = await response.json();

            if (!status.flinkJobRunning) {
                // 显示Flink未运行的提示
                showFlinkStoppedMessage();
                return false;
            }
            return true;
        } catch (error) {
            console.error('检查Flink状态失败:', error);
            return false;
        }
    }
    // 模拟数据生成（备用）
    function getMockData(district) {
        console.log(`生成 ${district} 的模拟数据`);
        const now = new Date();
        const data = [];
        const usedTimes = new Set();

        // 生成最近10分钟的数据
        for (let i = 9; i >= 0; i--) {
            const time = new Date(now.getTime() - i * 60 * 1000);
            const timeDisplay = time.getHours().toString().padStart(2, '0') + ':' +
                time.getMinutes().toString().padStart(2, '0');

            if (usedTimes.has(timeDisplay)) {
                continue;
            }
            usedTimes.add(timeDisplay);

            const baseTemp = getBaseTemperature(district);
            const timeFactor = Math.sin((time.getHours() + time.getMinutes() / 60.0) * Math.PI / 12) * 5;

            data.push({
                timeDisplay: timeDisplay,
                windSpeed: round(2.5 + (Math.random() - 0.5) * 1.5, 1),
                pressure: round(1013 + (Math.random() - 0.5) * 3, 1),
                temperature: round(baseTemp + timeFactor + (Math.random() - 0.5) * 2, 1),
                precipitation: Math.random() > 0.8 ? round(Math.random() * 1.5, 2) : 0,
                timestamp: time.toISOString()
            });
        }

        // 确保数据按时间排序
        data.sort((a, b) => {
            return convertTimeToMinutes(a.timeDisplay) - convertTimeToMinutes(b.timeDisplay);
        });

        return {
            district: district,
            data: data,
            lastUpdate: now.toISOString()
        };
    }

    // 获取区域基础温度
    function getBaseTemperature(district) {
        const baseTemps = {
            '中原区': 25.6,
            '二七区': 26.1,
            '管城回族区': 25.8,
            '金水区': 26.3,
            '上街区': 24.9,
            '惠济区': 25.2,
            '中牟县': 25.1,
            '巩义市': 24.8,
            '荥阳市': 25.4,
            '新密市': 25.0,
            '新郑市': 25.7,
            '登封市': 24.6
        };
        return baseTemps[district] || 25.0;
    }

    // 获取并更新所有图表
    async function fetchAndUpdateCharts(district) {
        const flinkRunning = await checkFlinkStatus();
        if (!flinkRunning) {
            return;
        }
        try {
            console.log(`正在获取 ${district} 的实时数据...`);

            // 立即更新当前地区，确保图表标题使用正确的地区名称
            currentDistrict = district;

            const result = await fetchRealTimeData(district);
            if (result && result.data) {
                console.log(`成功获取 ${district} 的数据，开始更新图表`);
                updateAllChartsWithRealData(result.data);

                // 更新最后更新时间显示
                updateLastUpdateTime(result.lastUpdate);

                console.log(`已更新 ${district} 的实时气象数据`);
            } else {
                console.error('获取的数据无效');
            }
        } catch (error) {
            console.error('更新图表数据失败:', error);
        }
    }

    // 计算动态纵坐标范围
    function calculateDynamicRange(data, type) {
        if (!data || data.length === 0) {
            // 默认范围
            const defaultRanges = {
                wind: { min: 0, max: 10 },
                pressure: { min: 1000, max: 1030 },
                temperature: { min: 20, max: 30 },
                precipitation: { min: 0, max: 5 }
            };
            return defaultRanges[type];
        }

        const min = Math.min(...data);
        const max = Math.max(...data);

        // 计算合适的范围，留出一些边距
        const range = max - min;
        const margin = range * 0.2; // 20%的边距

        let adjustedMin = min - margin;
        let adjustedMax = max + margin;

        // 根据数据类型设置最小值和特殊处理
        switch (type) {
            case 'wind':
                adjustedMin = Math.max(0, adjustedMin); // 风速不能为负
                adjustedMax = Math.max(adjustedMax, 2); // 确保有足够的显示范围
                break;
            case 'pressure':
                adjustedMin = Math.max(980, adjustedMin); // 气压合理范围
                adjustedMax = Math.min(1050, adjustedMax);
                break;
            case 'temperature':
                adjustedMin = Math.max(-10, adjustedMin); // 温度合理范围
                adjustedMax = Math.min(50, adjustedMax);
                break;
            case 'precipitation':
                adjustedMin = 0; // 降水不能为负
                adjustedMax = Math.max(adjustedMax, 0.5); // 确保有足够的显示范围
                break;
        }

        // 取整
        adjustedMin = Math.floor(adjustedMin * 10) / 10;
        adjustedMax = Math.ceil(adjustedMax * 10) / 10;

        console.log(`${type} 数据范围: ${min}-${max}, 调整后: ${adjustedMin}-${adjustedMax}`);

        return { min: adjustedMin, max: adjustedMax };
    }

    // 使用真实数据更新图表
    function updateAllChartsWithRealData(weatherData) {
        if (!weatherData || !Array.isArray(weatherData)) {
            console.error('无效的天气数据');
            return;
        }

        // 数据去重和排序处理
        const processedData = processWeatherData(weatherData);

        // 提取处理后的时间轴和数据
        const times = processedData.map(item => item.timeDisplay);
        const windData = processedData.map(item => item.windSpeed || 0);
        const pressureData = processedData.map(item => item.pressure || 0);
        const temperatureData = processedData.map(item => item.temperature || 0);
        const precipitationData = processedData.map(item => item.precipitation || 0);

        console.log('更新图表数据:', {
            times: times,
            windData: windData,
            pressureData: pressureData,
            temperatureData: temperatureData,
            precipitationData: precipitationData,
            dataCount: processedData.length
        });

        // 计算动态纵坐标范围
        const windRange = calculateDynamicRange(windData, 'wind');
        const pressureRange = calculateDynamicRange(pressureData, 'pressure');
        const temperatureRange = calculateDynamicRange(temperatureData, 'temperature');
        const precipitationRange = calculateDynamicRange(precipitationData, 'precipitation');

        // 计算x轴间隔
        const xAxisInterval = calculateXAxisInterval(times.length);

        // 更新所有图表
        updateChartData(chart1, times, windData, xAxisInterval, chartColors.wind, '风速', windRange,currentDistrict);
        updateChartData(chart2, times, pressureData, xAxisInterval, chartColors.pressure, '气压', pressureRange,currentDistrict);
        updateChartData(chart3, times, temperatureData, xAxisInterval, chartColors.temperature, '温度', temperatureRange,currentDistrict);
        updateChartData(chart4, times, precipitationData, xAxisInterval, chartColors.precipitation, '降水', precipitationRange,currentDistrict);
    }

    // 数据处理函数：去重、排序、验证
    function processWeatherData(weatherData) {
        if (!weatherData || !Array.isArray(weatherData)) {
            return [];
        }

        const validData = weatherData.filter(item =>
            item &&
            item.timeDisplay &&
            typeof item.timeDisplay === 'string' &&
            item.timeDisplay.trim() !== ''
        );

        if (validData.length === 0) {
            console.warn('没有有效的数据');
            return [];
        }

        const timeMap = new Map();

        validData.forEach(item => {
            const timeKey = item.timeDisplay.trim();
            if (!timeMap.has(timeKey)) {
                timeMap.set(timeKey, item);
            } else {
                const existing = timeMap.get(timeKey);
                if (item.timestamp && existing.timestamp) {
                    if (new Date(item.timestamp) > new Date(existing.timestamp)) {
                        timeMap.set(timeKey, item);
                    }
                }
            }
        });

        const uniqueData = Array.from(timeMap.values());

        uniqueData.sort((a, b) => {
            const timeA = convertTimeToMinutes(a.timeDisplay);
            const timeB = convertTimeToMinutes(b.timeDisplay);
            return timeA - timeB;
        });

        console.log(`数据处理: 原始${weatherData.length}条 -> 有效${validData.length}条 -> 去重后${uniqueData.length}条`);

        return uniqueData;
    }

    // 将时间字符串转换为分钟数用于排序
    function convertTimeToMinutes(timeStr) {
        if (!timeStr || typeof timeStr !== 'string') return 0;

        try {
            const [hours, minutes] = timeStr.split(':').map(Number);
            return (hours || 0) * 60 + (minutes || 0);
        } catch (error) {
            console.warn(`时间格式解析错误: ${timeStr}`, error);
            return 0;
        }
    }

    // 计算x轴间隔
    function calculateXAxisInterval(dataLength) {
        if (dataLength <= 5) return 0;
        if (dataLength <= 10) return 1;
        return Math.floor(dataLength / 5);
    }

    // 统一的图表更新函数
    function updateChartData(chart, times, data, interval, color, seriesName, range,district) {
        if (!chart) return;

        chart.setOption({
            title: {
                text: seriesName + ' - ' + district
            },
            yAxis: {
                min: range.min,
                max: range.max
            },
            xAxis: {
                data: times,
                interval: interval
            },
            series: [{
                type: 'line',
                name: seriesName,
                data: data,
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                    color: color,
                    width: 2
                },
                itemStyle: {
                    color: color
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: `${color}33` },
                        { offset: 1, color: `${color}11` }
                    ])
                }
            }]
        }, {
            replaceMerge: ['title', 'xAxis', 'series', 'yAxis']
        });
    }

    // 更新最后更新时间显示
    function updateLastUpdateTime(timestamp) {
        const updateElement = document.getElementById('lastUpdateTime');
        if (updateElement) {
            const time = new Date(timestamp);
            updateElement.textContent = '最后更新: ' +
                time.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
        }
    }

    // 初始化风况图表（使用动态范围）
    function initWindChart() {
        const chartElement = document.getElementById('echart1-realtime');
        if (!chartElement) {
            console.error('未找到风况图表容器 echart1-realtime');
            return;
        }

        chart1 = echarts.init(chartElement);

        const option = {
            title: {
                text: '风速 (m/s) - {区域}',
                textStyle: {
                    color: '#fff',
                    fontSize: 12,
                    fontWeight: 'normal'
                },
                left: 'center',
                top: '5%'
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#777',
                borderWidth: 1,
                textStyle: {
                    color: '#fff'
                },
                formatter: function(params) {
                    return params[0].name + '<br/>' +
                        '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + chartColors.wind + '"></span>' +
                        '风速: ' + params[0].value + ' m/s';
                }
            },
            grid: {
                left: '8%',
                right: '8%',
                bottom: '15%',
                top: '25%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: [],
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 10,
                    interval: 0,
                    rotate: 45
                },
                axisTick: {
                    show: false
                }
            },
            yAxis: {
                type: 'value',
                name: 'm/s',
                nameTextStyle: {
                    color: '#fff',
                    fontSize: 10
                },
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 10
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,0.1)',
                        type: 'dashed'
                    }
                },
                min: 0, // 初始最小值
                max: 10 // 初始最大值
            },
            series: [{
                name: '风速',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                    color: chartColors.wind,
                    width: 2
                },
                itemStyle: {
                    color: chartColors.wind
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(76, 209, 55, 0.3)' },
                        { offset: 1, color: 'rgba(76, 209, 55, 0.1)' }
                    ])
                },
                data: []
            }]
        };

        chart1.setOption(option);
    }

    // 初始化气压图表（使用动态范围）
    function initPressureChart() {
        const chartElement = document.getElementById('echart2-realtime');
        if (!chartElement) {
            console.error('未找到气压图表容器 echart2-realtime');
            return;
        }

        chart2 = echarts.init(chartElement);

        const option = {
            title: {
                text: '气压 (hPa)- {区域}',
                textStyle: {
                    color: '#fff',
                    fontSize: 12,
                    fontWeight: 'normal'
                },
                left: 'center',
                top: '5%'
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#777',
                borderWidth: 1,
                textStyle: {
                    color: '#fff'
                },
                formatter: function(params) {
                    return params[0].name + '<br/>' +
                        '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + chartColors.pressure + '"></span>' +
                        '气压: ' + params[0].value + ' hPa';
                }
            },
            grid: {
                left: '8%',
                right: '8%',
                bottom: '15%',
                top: '25%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: [],
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 10,
                    interval: 0,
                    rotate: 45
                },
                axisTick: {
                    show: false
                }
            },
            yAxis: {
                type: 'value',
                name: 'hPa',
                nameTextStyle: {
                    color: '#fff',
                    fontSize: 10
                },
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 10
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,0.1)',
                        type: 'dashed'
                    }
                },
                min: 1000, // 初始最小值
                max: 1030  // 初始最大值
            },
            series: [{
                name: '气压',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                    color: chartColors.pressure,
                    width: 2
                },
                itemStyle: {
                    color: chartColors.pressure
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
                        { offset: 1, color: 'rgba(255, 107, 107, 0.1)' }
                    ])
                },
                data: []
            }]
        };

        chart2.setOption(option);
    }

    // 初始化温度图表（使用动态范围）
    function initTemperatureChart() {
        const chartElement = document.getElementById('echart4-realtime');
        if (!chartElement) {
            console.error('未找到温度图表容器 echart4-realtime');
            return;
        }

        chart3 = echarts.init(chartElement);

        const option = {
            title: {
                text: '温度 (°C)- {区域}',
                textStyle: {
                    color: '#fff',
                    fontSize: 12,
                    fontWeight: 'normal'
                },
                left: 'center',
                top: '5%'
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#777',
                borderWidth: 1,
                textStyle: {
                    color: '#fff'
                },
                formatter: function(params) {
                    return params[0].name + '<br/>' +
                        '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + chartColors.temperature + '"></span>' +
                        '温度: ' + params[0].value + ' °C';
                }
            },
            grid: {
                left: '8%',
                right: '8%',
                bottom: '15%',
                top: '25%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: [],
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 10,
                    interval: 0,
                    rotate: 45
                },
                axisTick: {
                    show: false
                }
            },
            yAxis: {
                type: 'value',
                name: '°C',
                nameTextStyle: {
                    color: '#fff',
                    fontSize: 10
                },
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 10
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,0.1)',
                        type: 'dashed'
                    }
                },
                min: 20, // 初始最小值
                max: 30  // 初始最大值
            },
            series: [{
                name: '温度',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                    color: chartColors.temperature,
                    width: 2
                },
                itemStyle: {
                    color: chartColors.temperature
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(243, 156, 18, 0.3)' },
                        { offset: 1, color: 'rgba(243, 156, 18, 0.1)' }
                    ])
                },
                data: []
            }]
        };

        chart3.setOption(option);
    }

    // 初始化降水图表（使用动态范围）
    function initPrecipitationChart() {
        const chartElement = document.getElementById('echart5-realtime');
        if (!chartElement) {
            console.error('未找到降水图表容器 echart5-realtime');
            return;
        }

        chart4 = echarts.init(chartElement);

        const option = {
            title: {
                text: '降水 (mm)- {区域}',
                textStyle: {
                    color: '#fff',
                    fontSize: 12,
                    fontWeight: 'normal'
                },
                left: 'center',
                top: '5%'
            },
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#777',
                borderWidth: 1,
                textStyle: {
                    color: '#fff'
                },
                formatter: function(params) {
                    return params[0].name + '<br/>' +
                        '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + chartColors.precipitation + '"></span>' +
                        '降水: ' + params[0].value + ' mm';
                }
            },
            grid: {
                left: '8%',
                right: '8%',
                bottom: '15%',
                top: '25%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: [],
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 10,
                    interval: 0,
                    rotate: 45
                },
                axisTick: {
                    show: false
                }
            },
            yAxis: {
                type: 'value',
                name: 'mm',
                nameTextStyle: {
                    color: '#fff',
                    fontSize: 10
                },
                axisLine: {
                    lineStyle: {
                        color: '#fff'
                    }
                },
                axisLabel: {
                    color: '#fff',
                    fontSize: 10
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(255,255,255,0.1)',
                        type: 'dashed'
                    }
                },
                min: 0, // 初始最小值
                max: 5  // 初始最大值
            },
            series: [{
                name: '降水',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: {
                    color: chartColors.precipitation,
                    width: 2
                },
                itemStyle: {
                    color: chartColors.precipitation
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(46, 134, 222, 0.3)' },
                        { offset: 1, color: 'rgba(46, 134, 222, 0.1)' }
                    ])
                },
                data: []
            }]
        };

        chart4.setOption(option);
    }

    // 启动自动刷新
    function startAutoRefresh() {
        // 每分钟刷新一次
        autoRefreshInterval = setInterval(() => {
            fetchAndUpdateCharts(currentDistrict);
        }, 60000);

        console.log('自动刷新已启动，间隔: 60秒');
    }

    // 停止自动刷新
    function stopAutoRefresh() {
        if (autoRefreshInterval) {
            clearInterval(autoRefreshInterval);
            autoRefreshInterval = null;
            console.log('自动刷新已停止');
        }
    }

    // 窗口调整大小时重绘图表
    $(window).on('resize', function() {
        if (chart1) chart1.resize();
        if (chart2) chart2.resize();
        if (chart3) chart3.resize();
        if (chart4) chart4.resize();
    });

    // 暴露更新函数给地图点击事件
    window.updateWeatherCharts = function(district) {
        console.log(`地图点击事件: 切换到 ${district} 数据`);
        fetchAndUpdateCharts(district);
    };

    // 辅助函数：四舍五入
    function round(value, decimals) {
        return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
    }

    // 添加最后更新时间显示元素
    function addLastUpdateElement() {
        const weatherDiv = document.querySelector('.weather');
        if (weatherDiv && !document.getElementById('lastUpdateTime')) {
            const updateElement = document.createElement('div');
            updateElement.id = 'lastUpdateTime';
            updateElement.style.cssText = `
                color: #fff;
                font-size: 12px;
                margin-top: 5px;
                text-align: center;
            `;
            updateElement.textContent = '最后更新: --:--:--';
            weatherDiv.appendChild(updateElement);
        }
    }

    // 主初始化函数
    function init() {
        console.log('开始初始化实时气象图表...');
        initAllCharts();
        console.log('实时气象图表初始化完成');

        // 添加最后更新时间显示
        addLastUpdateElement();
    }

    // 页面卸载时清理
    $(window).on('beforeunload', function() {
        stopAutoRefresh();
    });

    // 延迟初始化
    setTimeout(init, 100);
});